// --------------------------------------------------------------------
// 线程池封装的实现
// --------------------------------------------------------------------

#include "threadpool.hpp"
#include "../common.hpp"
#include <cstring>


namespace ymbxUtil
{
#if __cplusplus < 201103L
    Thread::Thread(int num, threadHandler handler, void *args) : _handler(handler), _args(args)
    {
        ymbxSock::CreateLog("thread");
        _name = "thread_" + std::to_string(num);
        int ret = pthread_create(&_tid, 0, runhelper, this);
        if (ret != 0)
        {
            LOG_ERROR("thread", "线程", _name, "创建失败");
        }
        _status = threadStatus::RUNNING;
    }
    pthread_t Thread::getID()
    {
        if (_status == threadStatus::RUNNING)
        {
            return _tid;
        }
        return 0;
    }
    int Thread::status()
    {
        return _status;
    }
    void Thread::operator()()
    {
        if (_handler != nullptr)
        {
            _handler(_args);
        }
    }
    std::string Thread::threadName() { return _name; }
    void Thread::join()
    {
        int ret = pthread_join(_tid, nullptr);
        if (ret != 0)
        {
            LOG_ERROR("thread", "线程", _name, "等待失败");
        }
    }
    void Thread::detach()
    {
        int ret = pthread_detach(_tid);
        if (ret != 0)
        {
            LOG_ERROR("thread", "线程", _name, "分离失败");
        }
    }
    Thread::~Thread()
    {
        _status = threadStatus::EXITED;
    }
#endif
}